import { defineConfig,loadEnv } from 'vite'
import path from "path";
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

const pathSrc = path.resolve(__dirname, "src");
const envDir = path.resolve(__dirname, "env");
/**
 * 根据内容views组件相对路径，生成 动态组件路径对象，帮助动态导入组件，避免动态组件中的相对路径使用
 * @param viewsRelativePath AppMain.vue中的components 相对路径，即主要内容区组件的相对路径，如"src/views"
 */
function bulidViewsPath(viewsRelativePath: string) {
    //如：D:\Front_End\Gitee\gui_gu_admin_combine_ts\src，在js 字符串中 \ 为转义符
    const viewPathIllegal = path.resolve(__dirname, viewsRelativePath)

    const viewsPathObj = { viewsAbsPath: '', viewsRelPath: '', viewsVueAbsPathPattern: '' }
    // viewsAbsPath 属性用在alias 中
    //替换后 D:/Front_End/Gitee/gui_gu_admin_combine_ts/src/views
    //用在后面动态导入，import.meta.glob 语法只支持 字面量，不支持变量
    viewsPathObj.viewsAbsPath = viewPathIllegal.replace(/\\/g, '/')
    //viewRelPath 属性用在define 全局变量
    //示例:/src/views
    //用于拼接 const moudlues=import.meta.glob(...) 中 moudlues的key
    viewsPathObj.viewsRelPath = viewsPathObj.viewsAbsPath.substring(
        viewsPathObj.viewsAbsPath.indexOf('/src'),
    )
    // viewVueAbsPathPattern： 为import.meta.glob(viewVueAbsPathPattern) 绝对路径参数
    //如 D:/Front_End/Gitee/gui_gu_admin_combine_ts/src/views/**/**/.vue
    viewsPathObj.viewsVueAbsPathPattern = viewsPathObj.viewsAbsPath + '/**/**_index.vue'
    return viewsPathObj
}

const viewsPathObj = bulidViewsPath('src/views')

// https://vitejs.dev/config/
export default defineConfig(({mode})=>{
    // const env = loadEnv(mode,envDir);
    const env = loadEnv(mode, process.cwd());
    console.log(env);
    
    return {
        resolve: {
            alias: {
                "@": path.resolve(__dirname, "./src")
            }
        },
        define: {
            GLOBAL_VAR: { test: 'i am global var from vite.config.js define' },
            //作为 拼接 const moudlues=import.meta.glob(...) 中 moudlues的key的前缀
            //将 src/views 增加双引号
            VITE_GLOBAL_VAR_VIEWS_REL_PATH: JSON.stringify(viewsPathObj.viewsRelPath),
        },
        css: {
            preprocessorOptions: {
                less: {
                    // additionalData:"import "+path.resolve(__dirname, "./styles/mixin.less"),
                    //'@import "./src/assets/style/global.less";'
                    additionalData: '@import "./src/styles/mixin.less";',
                },
                scss: {
                    // additionalData:"import "+path.resolve(__dirname, "./styles/mixin.less"),
                    //'@import "./src/assets/style/global.less";'
                    additionalData:
                        '@import "./src/styles/global_variables.module.scss";',
                },
            },
        },
        server: {
            // 允许IP访问
            host: '0.0.0.0',
            // 应用端口 (默认:3000)
             port:10001,//这个是前端的端口
            open: true,
            proxy: {
                /**
                 * 反向代理解决跨域配置
                 * http://localhost:3000/dev-api/users (F12可见请求路径) => http://localhost:8989/users (实际请求后端 API 路径)
                 *
                 * env.VITE_APP_BASE_API: /dev-api
                 * env.VITE_APP_TARGET_URL: http://localhost:3000
                 * env.VITE_APP_TARGET_BASE_API: ""
                 */

                //以此前缀开始的url,代理规则
                [env.VITE_APP_API_PREFIX]: {
                    changeOrigin: true,
                    target: env.VITE_APP_TARGET_URL_NSL,//访问的目标url
                    // target: "https://www.baidu.com",

                    //重写url
                    rewrite: (path) =>
                        path.replace(
                            new RegExp('^' +env.VITE_APP_API_PREFIX),
                            '',
                        ),
                },
            },
        },
        plugins: [
            vue(),
            createSvgIconsPlugin({
                // 指定需要缓存的图标文件夹
                iconDirs: [path.resolve(pathSrc, "assets/svg_icons")],
                // 指定symbolId格式,
                //这里dir为目录，如果是根目录的话为空，貌似只支持一级子目录
                //name为文件名
                symbolId: "icon-[dir]-[name]",
            }),
        ],
    }
})
